<template>
  <div class="content">
    <div class="header">
      <el-input
        label="題目"
        v-model="title"
        placeholder="请输入题目"
        style="width: 200px"
      />
      <el-input
        label="描述"
        v-model="description"
        placeholder="请输入相关描述"
        style="width: 200px"
      />
      <el-select
        label="分类"
        v-model="categoryIds"
        multiple
        filterable
        allow-create
        default-first-option
        :reserve-keyword="false"
        placeholder="请选择相关分类"
        style="width: 500px"
      >
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>

      <el-upload
        class="avatar-uploader"
        action="#"
        :show-file-list="false"
        :on-change="onChange"
        :before-upload="beforeAvatarUpload"
      >
        <el-button>选择图片</el-button>
      </el-upload>
    </div>
    <v-md-editor
      v-model="content"
      height="400px"
      :disabled-menus="[]"
      @upload-image="handleUploadImage"
    ></v-md-editor>
    <div class="but">
      <el-button type="primary" @click="cancle">取消</el-button>
      <el-button type="primary" @click="save">发布</el-button>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import { addBlog, updateBlog } from "@/api/blog";
import { getAll } from "@/api/category";
import { upload } from "@/api/file";
import { ElMessage } from "element-plus";
export default {
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      isEditBlog: this.$store.getters.getIsEditBlog,
      options: [],
      title: "",
      description: "",
      categoryIds: [],
      content: "",
      img: "https://zzzzzzzzzzzzzzzzzzzzzzzzz.oss-cn-hangzhou.aliyuncs.com/%E6%88%91%E6%84%BF%E6%88%90%E4%B8%BA%E4%B8%80%E6%9D%A1%E6%B2%B3.png",
    };
  },
  created() {
    this.getAllCategory();
  },
  mounted() {
    if (this.isEditBlog) {
      const blogCategory = this.$store.getters.getEditBlogInfo;
      this.title = blogCategory.title;
      this.description = blogCategory.description;
      this.content = blogCategory.content;
      const categories = blogCategory.categories;
      for (let i = 0; i < categories.length; i++) {
        const category = categories[i];
        this.categoryIds.push(category.id);
      }
      console.log(blogCategory);
      console.log(this.categoryIds);
    }
    console.log("mounted : " + this.isEditBlog);
  },
  methods: {
    getAllCategory() {
      getAll(this.userInfo.id).then((res) => {
        if (res.code == 200) {
          this.options = res.data;
        }
      });
    },
    beforeAvatarUpload(rawFile) {
      console.log(rawFile.type);
      if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("Avatar picture must be JPG or PNG format!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      } else {
        let formData = new FormData();
        formData.append("file", rawFile);
        upload(formData).then((res) => {
          if (res.code == 200) {
            this.img = res.data;
            console.log(res.data);
          }
        });
      }
      return false;
    },
    save() {
      const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      const addData = {
        blog: {
          content: this.content,
          created: "",
          description: this.description,
          recommend: 0,
          status: 0,
          title: this.title,
          userId: userInfo.id,
          img: this.img,
        },
        categoryIds: this.categoryIds,
      };
      if (addData.blog.content == "" || addData.blog.title == "") {
        ElMessage.error("标题或者内容不能为空");
      } else if (addData.categoryIds.length == 0) {
        ElMessage.error("请选择相关分类");
      } else {
        if (this.isEditBlog) {
          const blogCategory = this.$store.getters.getEditBlogInfo;
          console.log(blogCategory.img == "");
          console.log(blogCategory.img == null);
          const updateData = {
            blog: {
              content: this.content,
              created: "",
              description: this.description,
              recommend: blogCategory.recommend == true ? 1 : 0,
              id: blogCategory.id,
              status: blogCategory.status,
              title: this.title,
              userId: userInfo.id,
              img: blogCategory.img == null || "" ? this.img : blogCategory.img,
            },
            categoryIds: this.categoryIds,
          };
          console.log(updateData);
          updateBlog(updateData).then((res) => {
            console.log(updateData);
            if (res.code == 200) {
              ElMessage.success("修改文章成功");
              this.$router.push("/blog");
              this.$store.commit("SET_ISEDITBLOG", false);
            } else {
              ElMessage.error(res.msg);
            }
          });
          console.log(updateData);
        } else {
          addBlog(addData).then((res) => {
            if (res.code == 200) {
              ElMessage.success("新增文章成功");
            } else {
              ElMessage.error(res.msg);
            }
          });
        }
      }
    },
    cancle() {
      if (this.isEditBlog) {
        this.$router.push("/blog");
        this.$store.commit("SET_ISEDITBLOG", false);
      } else {
        (this.options = []),
          (this.title = ""),
          (this.description = ""),
          (this.categoryIds = []),
          (this.content = ""),
          ElMessage.success("取消");
      }
    },
    handleUploadImage(event, insertImage, files) {
      console.log(files[0]);
      let formData = new FormData();
      formData.append("file", files[0]);
      upload(formData).then((res) => {
        if (res.code == 200) {
          ElMessage.success("上传图片成功");
          const url = res.data;
          insertImage({
            url: url,
            desc: files[0].name,
            width: "auto",
            height: "auto",
          });
        } else {
          ElMessage.error(res.msg);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  text-align: left;
  .header {
    display: flex;
    justify-content: space-around;
    margin: 10px;
  }

  .but {
    display: flex;
    justify-content: center;
    margin: 10px;
  }
}
</style>
